/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import java.awt.event.FocusEvent;
import modelo.DatosIngresosTableModel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import persistencia.AtiendeDAO;
import persistencia.IngresosDAO;
import persistencia.ProcesoasistencialDAO;
import pojos.Atiende;
import pojos.Ingresos;
import pojos.Procesoasistencial;

/**
 *
 * @author Administrator
 */
public class PanelIngresos extends javax.swing.JPanel {

    Vector vNombresColumnas = new Vector();
    Vector<Ingresos> vIngresos = new Vector();
    IngresosDAO gestorIngresos = new IngresosDAO();
    int lastSelectedRow = -1;
    VentanaPrincipal vp;

    /**
     * Creates new form GestionIngresos
     */
    public PanelIngresos(VentanaPrincipal vp) {
        initComponents();
        this.vp = vp;
        this.jComboBoxTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"CodPaciente", "DNI", "IdIngreso", "Fecha Ingreso", "Fecha Alta", "IdPA"}));

        vNombresColumnas.add("idIngreso");
        vNombresColumnas.add("fechaIngreso");
        vNombresColumnas.add("fechaAlta");
        vNombresColumnas.add("idPA");

        vIngresos = gestorIngresos.searchAll();
        DatosIngresosTableModel ditm = new DatosIngresosTableModel(vIngresos, vNombresColumnas);

        jTableIngresos.setModel(ditm);

        seleccionListener();
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPaneIngresos = new javax.swing.JScrollPane();
        jTableIngresos = new javax.swing.JTable();
        jButtonBuscar = new javax.swing.JButton();
        jComboBoxTipo = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        jTextFieldDato = new javax.swing.JTextField();
        jToolBar1 = new javax.swing.JToolBar();
        jButtonAdd = new javax.swing.JButton();
        jButtonEdit = new javax.swing.JButton();
        jButtonDelete = new javax.swing.JButton();

        jLabel1.setText("Ingresos");

        jTableIngresos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPaneIngresos.setViewportView(jTableIngresos);

        jButtonBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_find.png"))); // NOI18N
        jButtonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarActionPerformed(evt);
            }
        });

        jComboBoxTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel8.setText("Tipo:");

        jToolBar1.setRollover(true);

        jButtonAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_plus.png"))); // NOI18N
        jButtonAdd.setFocusable(false);
        jButtonAdd.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonAdd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddActionPerformed(evt);
            }
        });
        jToolBar1.add(jButtonAdd);

        jButtonEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_edit1.png"))); // NOI18N
        jButtonEdit.setFocusable(false);
        jButtonEdit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonEdit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEditActionPerformed(evt);
            }
        });
        jToolBar1.add(jButtonEdit);

        jButtonDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_bin.png"))); // NOI18N
        jButtonDelete.setFocusable(false);
        jButtonDelete.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonDelete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteActionPerformed(evt);
            }
        });
        jToolBar1.add(jButtonDelete);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPaneIngresos, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addGap(18, 18, 18)
                                .addComponent(jComboBoxTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jTextFieldDato, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButtonBuscar))
                            .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 584, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8)
                    .addComponent(jTextFieldDato, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonBuscar))
                .addGap(83, 83, 83)
                .addComponent(jScrollPaneIngresos, javax.swing.GroupLayout.PREFERRED_SIZE, 416, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents


    private void jButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarActionPerformed
        // TODO add your handling code here:
        String filtro = this.jTextFieldDato.getText().toString();
        switch (this.jComboBoxTipo.getSelectedIndex()) {
            case 0:
                vIngresos = gestorIngresos.searchByCodPaciente(filtro);
                cambiarModeloTable();
                break;
            case 1:
                vIngresos = gestorIngresos.searchByDNI(filtro);
                cambiarModeloTable();
                break;
            case 2:
                vIngresos = gestorIngresos.searchByIdIngreso(filtro);
                cambiarModeloTable();
                break;
            case 3:
                vIngresos = gestorIngresos.searchByFechaIngreso(filtro);
                cambiarModeloTable();
                break;
            case 4:
                vIngresos = gestorIngresos.searchByFechaAlta(filtro);
                cambiarModeloTable();
                break;
            case 5:
                vIngresos = gestorIngresos.searchByIdPA(filtro);
                cambiarModeloTable();
                break;

        }
        seleccionListener();
    }//GEN-LAST:event_jButtonBuscarActionPerformed

    private void jButtonEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEditActionPerformed
        // TODO add your handling code here:
        if (lastSelectedRow != -1) {
            Integer idIngreso = (Integer) this.jTableIngresos.getValueAt(lastSelectedRow, 0);
            JDialogModIngreso modIngreso = new JDialogModIngreso(this, idIngreso);
            modIngreso.setVisible(true);
            vIngresos = gestorIngresos.searchAll();
            cambiarModeloTable();
        } else {
            JOptionPane.showMessageDialog(this, "No seleccionado ingreso.");
        }
    }//GEN-LAST:event_jButtonEditActionPerformed

    private void jButtonAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddActionPerformed
        // TODO add your handling code here:
        JDialogAddIngreso newIngreso = new JDialogAddIngreso(this);
        newIngreso.setVisible(true);
        vIngresos = gestorIngresos.searchAll();
        cambiarModeloTable();
    }//GEN-LAST:event_jButtonAddActionPerformed

    private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteActionPerformed
        // TODO add your handling code here:
        if (lastSelectedRow != -1) {
            Integer idIngreso = (Integer) this.jTableIngresos.getValueAt(lastSelectedRow, 0);
            Ingresos i = new IngresosDAO().obtenIngresoPorId(idIngreso);
            int opcionElegida;
            opcionElegida = JOptionPane.showConfirmDialog(this, "¿Esta seguro que desea eliminar este ingreso?");
            if (opcionElegida == JOptionPane.OK_OPTION) {
                new IngresosDAO().eliminaIngresos(i);
                Atiende ae = new AtiendeDAO().obtenAtiendePoridPA(i.getProcesoasistencial().getIdPa());
                new AtiendeDAO().eliminaAtiende(ae);
                Procesoasistencial pe = new ProcesoasistencialDAO().obtenProcesoasistencial(i.getProcesoasistencial().getIdPa());
                new ProcesoasistencialDAO().eliminaProcesoasistencial(pe);
                JOptionPane.showMessageDialog(this, "Has eliminado correctamente");
                vIngresos = gestorIngresos.searchAll();
                cambiarModeloTable();
            } else if (opcionElegida == JOptionPane.NO_OPTION) {
                JOptionPane.showMessageDialog(this, "No has eliminado");
            } else if (opcionElegida == JOptionPane.CANCEL_OPTION) {
                JOptionPane.showMessageDialog(this, "Has cancelado la operacion");
            }
        } else {
            JOptionPane.showMessageDialog(this, "No seleccionado ingreso.");
        }
    }//GEN-LAST:event_jButtonDeleteActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAdd;
    private javax.swing.JButton jButtonBuscar;
    private javax.swing.JButton jButtonDelete;
    private javax.swing.JButton jButtonEdit;
    private javax.swing.JComboBox jComboBoxTipo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPaneIngresos;
    private javax.swing.JTable jTableIngresos;
    private javax.swing.JTextField jTextFieldDato;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration//GEN-END:variables

    private void cambiarModeloTable() {

        DatosIngresosTableModel ditm = new DatosIngresosTableModel(vIngresos, vNombresColumnas);

        jTableIngresos.setModel(ditm);
    }

    private void seleccionListener() {
        this.jTableIngresos.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e); //To change body of generated methods, choose Tools | Templates.
                changeSelectedRow(jTableIngresos.getSelectedRow());
            }

        });
        this.jTableIngresos.setCellSelectionEnabled(true);
        ListSelectionModel cellSelectionModel = this.jTableIngresos.getSelectionModel();
        cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (jTableIngresos.getSelectedRow() != lastSelectedRow) {
                    changeSelectedRow(jTableIngresos.getSelectedRow());
                }
            }
        });
        this.jTableIngresos.setSelectionModel(cellSelectionModel);
    }

    private void changeSelectedRow(int newSelectedRowId) {
        lastSelectedRow = newSelectedRowId;
    }
}
